//
//  TGMListModel.m
//  TravelGuideMdd
//
//  Created by BigPolarBear on 3/3/14.
//  Copyright (c) 2014 mafengwo.com. All rights reserved.
//

#import "TGMListModel.h"

@implementation TGMListModel

- (Class)classOfItem
{
    [NSException raise:@"NotImplemented:" format:@"[%@]classOfItem:",NSStringFromClass([self class])];
    
    return nil;
}

- (Class)classOfModelItemForDataId:(NSString*)dataId;
{
    return [self classOfItem];
}

- (NSString*)keyOfPersistentCacheForDataId:(NSString *)dataId
{
    return [NSString stringWithFormat:@"%@_%@", NSStringFromClass([self class]),dataId];
}

- (BOOL)bSupportPersistentCache:(NSString*)dataId
{
    return YES;
}


-(NSString*)dataIdOfParams:(NSDictionary*)params
{
    MFWJson* json =  [MFWJson jsonWithObject:params];
    NSString* strJson = [json stringJson];
    return strJson?strJson:mfwDefaultDataId;
}

-(NSDictionary*)paramsOfDataId:(NSString*)dataId
{
    MFWJson* json = [MFWJson jsonWithString:dataId];
    if ([json.jsonObj isKindOfClass:[NSDictionary class]]) {
        return json.jsonObj;
    }else{
        return nil;
    }
}

- (NSMutableDictionary*)dictWithValueUrlEncoded:(NSDictionary*)dict
{
    NSMutableDictionary* retDict = [NSMutableDictionary dictionary];
    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString* value = obj;
        retDict[key] = [value urlEncode];
    }];
    
    return retDict;
}

- (MFWHttpTask*)requestRefresh:(TGMBaseModelActionData *)data
{
   return  [self requestRefresh:data completion:nil];
}

- (MFWHttpTask*)requestGetMore:(TGMBaseModelActionData *)data
{
    return  [self requestGetMore:data completion:nil];
}

-(MFWHttpTask *)requestRefresh:(TGMBaseModelActionData*)data completion:(void(^)(BOOL success, NSArray *items,NSString* errorMsg))completion{
    
    MFWHttpTask *task = [MFWHttpTask task];
    NSString* dataId = data.dataId;
    task.dataIdentifier = [MFWDataIdentifier identifierOfCategory:[self.class categoryName]
                                                           dataId:dataId];
    task.dataRequestType = kMFWDataRequest_Refresh;
    task.argsDic = data.params.copy;
    task.block = completion;
    task.userInfo = data;
    if ([[MFWHttpEngine sharedInstance] addTask:task])
    {
        MFWDataStatus *dataStatus = [self dataStatusForDataId:dataId];
        dataStatus.statusType = kDataStatus_Refreshing;
        
        return task;
    }else{
        return nil;
    }
    
}

- (NSString*)lastOffsetForDataId:(NSString*)dataId;
{
    NSString *offset = nil;
    MFWJson *data = [self jsonDataForDataId:dataId];
    
    offset = [data stringValueForKey:@"offset" defaultValue:nil];
    
    return offset;
}

-(MFWHttpTask *)requestGetMore:(TGMBaseModelActionData *)data completion:(void (^)(BOOL, NSArray *, NSString *))completion{

    MFWHttpTask *task = [MFWHttpTask task];
    NSString* dataId = data.dataId;
    task.dataIdentifier = [MFWDataIdentifier identifierOfCategory:[self.class categoryName]
                                                           dataId:dataId];
    //DLog(@"%@",task.dataIdentifier);
    task.dataRequestType = kMFWDataREquest_GetMore;
    task.argsDic = [self dictWithValueUrlEncoded:data.params];
    task.block = completion;
    task.userInfo = data;
    if ([[MFWHttpEngine sharedInstance] addTask:task])
    {
        return task;
        
    }else{
        
        return nil;
    }
}

- (MFWHttpRequest*)mfwHttpRequestForTask:(MFWHttpTask*)task;
{
    MFWHttpRequest* request = [super mfwHttpRequestForTask:task];
    TGMBaseModelActionData *actionData = task.userInfo;
    request.requestUrl = actionData.apiUrl;
    request.httpMethod = actionData.httpMethod;
    
    NSString *offset = @"0";
    NSString *pageStartKey = @"start";
    
    if (task.dataRequestType == kMFWDataREquest_GetMore)
    {
        NSString *lastOffset = [self lastOffsetForDataId:task.dataIdentifier.dataId];
        if (lastOffset)
        {
            offset = [lastOffset copy];
        }
        else
        {
            NSUInteger start = [self countOfReceivedListDataForDataId:task.dataIdentifier.dataId];
            offset = [NSString stringWithFormat:@"%ld", start];
        }
    }
    
    if (actionData.pageStartKey.length)
    {
        pageStartKey = actionData.pageStartKey;
    }
    
    request.requestParams = [NSMutableDictionary dictionaryWithDictionary:task.argsDic];
    [request.requestParams setValue:offset
                             forKey:pageStartKey];
    
    if (actionData.pageLength > 0 && actionData.pageLengthKey.length > 0)
    {
        [request.requestParams setValue:[NSString stringWithFormat:@"%ld",actionData.pageLength]
                                 forKey:actionData.pageLengthKey];
    }
    
    return request;
}

- (BOOL)processServiceSuccRawData:(NSData *)rawData parsedJson:(MFWJson *)jsonObj forTask:(MFWHttpTask *)task
{
    return [super processServiceSuccRawData:rawData parsedJson:jsonObj forTask:task];
}
- (NSArray*)listModelItemForDataId:(NSString *)dataId
{
    return [super listModelItemForDataId:dataId];
}

- (BOOL)canGetMoreForDataId:(NSString*)dataId
{
    return [super canGetMoreForDataId:dataId];
}
- (NSNumber*)totalForDataId:(NSString*)dataId
{
    MFWJson* json = [self jsonDataForDataId:dataId];
    NSString* total = [json stringValueForKey:@"total"];
    if (total.length > 0) {
        return [NSNumber numberWithInteger:[total integerValue]];
    }else{
        return nil;
    }
}

/** 添加观察者 */
+ (void)addDataObserver:(id<MFWDataObserver>)anObserver
{
    [super addDataObserver:anObserver];
}
/** 删除观察者 */
+ (void)removeDataObserver:(id<MFWDataObserver>)anObserver
{
    [super removeDataObserver:anObserver];
}

@end
